package com.southwind.springboottest.study.Java读写锁;

import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @description：TODO Java读写锁 读写锁可以提高并发性能，允许多个线程同时进行读操作，但只允许一个线程进行写操作。
 * 使用ReentrantReadWriteLock封装的Map
 * ReentrantLock不能完全替代synchronized，只有在synchronized无法满足需求时，才应该使用它。
 * 读-写锁允许多个读线程并发地访问被保护的对象，当访问以读取操作为主的数据结构时， 它能提高程序
 * 的可伸缩性。
 * @author： HXG
 * @create： 2023/12/15 14:49
 */
public class ReadWriteMap<K, V> {
    private final Map<K, V> map; // 当然我们也可以封装一些别的集合类
    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    private final Lock r = lock.readLock();
    private final Lock w = lock.writeLock();
    public ReadWriteMap(Map<K, V> map) {
        this.map = map;
    }
    public V put(K key, V value) {
        w.lock();
        System.out.println(Thread.currentThread() + " is putting."); // for debug
        try {
            return map.put(key, value);
        } finally {
            w.unlock();
        }
    }
    public V get(Object key) {
        r.lock();
        System.out.println(Thread.currentThread() + " is getting.");
        try {
            return map.get(key);
        } finally {
            r.unlock();
        }
    }
    public void remove(Object key) {
        w.lock();
        System.out.println(Thread.currentThread() + " is remove.");
        try {
            map.remove(key);
        } finally {
            w.unlock();
        }
    }
    public void clear(Object key) {
        w.lock();
        System.out.println(Thread.currentThread() + " is remove.");
        try {
            map.clear();
        } finally {
            w.unlock();
        }
    }
    public Map<K,V> putALL( Map<K,V>  m) {
        w.lock();
        System.out.println(Thread.currentThread() + " is remove.");
        try {
            Map<K, V> kvMap = putALL(m);
            return kvMap;
        } finally {
            w.unlock();
        }
    }
}
